/**
 * 钉钉扫码登录
 * @version 2021-11-09 zzc
 */

class Dingtalk {
  goto: string
  backUrl: string
  state: number
  urlPreffix: string
  appid: string
  domain: string

  constructor() {
    // 文档地址：https://open.dingtalk.com/document/orgapp-server/scan-qr-code-to-log-on-to-third-party-websites
    this.state = Math.random()
    this.appid = 'dingfiesdgu1kmemgty2'
    this.domain = 'http://10.1.3.176:8080/'
    this.urlPreffix = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.appid}&response_type=code&scope=snsapi_login&state=`
    this.backUrl = encodeURIComponent(`${this.domain}appadmin/#/login`) // 扫码后跳转的地址
    this.goto = `${this.urlPreffix}${this.state}&redirect_uri=${this.backUrl}`
  }

  /**
   * 初始化钉钉二维码
   * @version 2023-06-19 zzc
   * @param { String } codeId 显示二维码的id
   * @param { Function } callback 回调
   */
  public init(codeId: string, callback?: Function) {
    const scriptEle = document.createElement('script')
    const win: any = window

    const handleMessage = (event: any) => {
      const { origin, data } = event
      if (origin === 'https://login.dingtalk.com') {
        const redirectUri = `${this.goto}&loginTmpCode=${data}`
        if (win.parent === window) {
          parent.location.href = redirectUri
        } else {
          win.parent.location.href = redirectUri
        }
      }
    }
    scriptEle.id = 'dinglogin'
    scriptEle.src = 'https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js'
    document.head.appendChild(scriptEle)

    scriptEle.onload = () => {
      // @ts-ignore
      DDLogin({
        id: codeId,
        goto: encodeURIComponent(this.goto),
        style: 'background-color: transparent;border: none',
        with: '210',
        height: '310',
      })
      callback && callback()
    }

    if (typeof win.addEventListener !== 'undefined') {
      win.addEventListener('message', handleMessage, false)
    } else if (typeof win.attachEvent !== 'undefined') {
      win.attachEvent('onmessage', handleMessage)
    }
  }

  /**
   * 钉钉扫码登陆
   * @param { Object } params 参数对象
   * @param { String } params.code code
   * @param { Object } params.state state
   * @version 2021-11-09 zzc
   */
  public async login(params) {
    const { code, state } = params
    if (!code || !state) {
      return
    }
    // UserApi.dingtalkLogin 是请求后端接口，这里改成你自己的
    // const { result } = await UserApi.dingtalkLogin(params)
    // // 这里进行扫码成功后的操作
    // return result
  }
}

export default new Dingtalk()
